(ns lensfield.triplestore
   (:import (java.io File)
            (org.openrdf.model Resource)
            (org.openrdf.repository.sail SailRepository)
            (org.openrdf.rio RDFFormat)
            (org.openrdf.sail.nativerdf NativeStore)))

(defmacro with-repo-connection
   "Takes a directory containing a triplestore and a one-arg fn where the
   arg is used to perform operations on a triplestore connection. Returns the 
   return value of f."
   [repo-loc f]
   `(let [repo# (SailRepository. (NativeStore. (File. ~repo-loc) "spoc,posc,cosp"))]
      (do
         (. repo# initialize))
      (let [con# (. repo# getConnection)]
         (try
            (~f con#)
            (finally
               (. con# close) 
               (. repo# shutDown))))))
               
(defn add-files
   "Add a seq of RDF files to a triplestore located in repo-loc using the 
   provided base-ref."
   [repo-loc files base-ref]
   (with-repo-connection repo-loc
      (fn [con] 
         (doseq [f files]
            (. con add f base-ref (RDFFormat/forFileName (. f getAbsolutePath)) (into-array Resource []))))))